package org.zachary.creditbusiness.hotel.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.zachary.creditbusiness.hotel.entity.Reservation;
import org.zachary.creditbusiness.hotel.service.ReservationService;
import org.zachary.creditbusiness.hotel.util.SendReservation;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@RestController
@RequestMapping("/hotels")
public class ReservationController {

    private final ReservationService reservationService;
    private static final DateTimeFormatter DTF = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");


    @Autowired
    public ReservationController(ReservationService reservationService) {
        this.reservationService = reservationService;
    }

    /**
     * 创建新预订（已存在）
     * POST /hotels/reservation
     */
    @PostMapping("/reservation")
    public Reservation createReservation(@RequestBody Reservation reservation) {
        // 下单时间按格式填充
        reservation.setBookDate(LocalDateTime.now().format(DTF));
        reservationService.save(reservation);
        return reservation;
    }

    /**
     * 获取某用户的所有预订
     * GET /hotels/reservation?userId={userId}
     */
    @GetMapping("/reservation")
    public List<Reservation> getByUser(@RequestParam Integer userId) {
        return reservationService.listByUserId(userId);
    }

    /**
     * 订单还款
     * PUT /hotels/reservation/{orderId}/repay
     */
    @PutMapping("/reservation/{orderId}/repay")
    public Reservation repay(@PathVariable Integer orderId) {
        return reservationService.repayReservation(orderId);
    }


    @DeleteMapping("/reservation/{orderId}")
    public ResponseEntity<Void> cancelReservation(@PathVariable Integer orderId) {
        boolean success = reservationService.cancelReservation(orderId);
        if (success) {
            // 204 No Content
            return ResponseEntity.noContent().build();
        } else {
            // 500 Internal Server Error
            return ResponseEntity
                    .status(500)
                    .build();
        }
    }
}